package com.example.demo.p1;
import java.io.IOException;
import java.net.URI;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.fasterxml.jackson.databind.ObjectMapper;

public class MyHandler extends TextWebSocketHandler {
	@Autowired
	ObjectMapper mapper;
	
	RestTemplate restTemplate = new RestTemplate();
	
	{
		restTemplate.setErrorHandler(new ResponseErrorHandler() {
			
			@Override
			public boolean hasError(ClientHttpResponse response) throws IOException {
				return false;
			}
			
			@Override
			public void handleError(ClientHttpResponse response) throws IOException {
			}
		});
	}
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        // ...
    	System.out.println("receive: " + message.getPayload());
    	try {
    		Req d = mapper.readValue(message.getPayload(), Req.class);
    		
    		String url = "http://localhost:8080" + d.getPath();
    		HttpMethod method = null;
    		if ("post".equalsIgnoreCase(d.getMethod())) {
    			method = HttpMethod.POST;
    		} else if ("put".equalsIgnoreCase(d.getMethod())) {
    			method = HttpMethod.PUT;
    		} else if ("delete".equalsIgnoreCase(d.getMethod())) {
    			method = HttpMethod.DELETE;
    		} else {
    			method = HttpMethod.GET;
    		}
    		RequestEntity<Object> requestEntity = new RequestEntity<>(method, new URI(url));
    		ResponseEntity<String> exchange = restTemplate.exchange(requestEntity, String.class);
    		Resp resp = new Resp();
    		resp.setStatusCode(exchange.getStatusCodeValue());
    		resp.setHeaders(exchange.getHeaders().toSingleValueMap());
    		resp.setData(exchange.getBody());
			session.sendMessage(new TextMessage(mapper.writeValueAsString(resp)));
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		System.out.println(session.getUri().getQuery());
		System.out.println("Connected by "+ session.getRemoteAddress());
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		System.out.println("Closed by "+ session.getRemoteAddress());
	}
    
    

}